package com.putao.web.advice;

import com.putao.result.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @author fuhehuang
 * @email 2628279194@qq.com
 */
@RestControllerAdvice
@Slf4j
public class ControllerAdvice {

    @ExceptionHandler(value = Exception.class)
    public JsonResult handler(Exception ex){
        if (ex instanceof MethodArgumentNotValidException){
            log.error("参数错误：{}", ex.getMessage());
            return JsonResult.<Void>argumentError(ex.getMessage(), null);
        }
        ex.printStackTrace();
        log.error("系统出现了异常：{}", ex.getMessage());
        return JsonResult.<Void>systemError(ex.getMessage(), null);
    }

    @ExceptionHandler(value = UsernameNotFoundException.class)
    public JsonResult handler(UsernameNotFoundException ex){
        ex.printStackTrace();
        log.error("认证出现错误：{}", ex.getMessage());
        return JsonResult.<Void>operationError(ex.getMessage(), ex.getMessage(), ex.getMessage());
    }

    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    public JsonResult handler(HttpRequestMethodNotSupportedException ex){
        ex.printStackTrace();
        String method = ex.getMethod();
        log.error("请求方式错误：{}", ex.getMessage());
        return JsonResult.<Void>operationError("当前请求不支持" + method + "请求方式,", ex.getMessage(), ex.getMessage());
    }

}
